package com.aruba.room;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

/**
 * Created by aruba on 2021/9/12.
 */
@Database(entities = {User.class}, version = 4, exportSchema = true)
public abstract class MyDataBase extends RoomDatabase {
    private static final String DBNAME = MyDataBase.class.getSimpleName();
    private static MyDataBase instance;

    public static MyDataBase getInstance() {
        if (instance == null) throw new NullPointerException("database not init!!");
        return instance;
    }

    public static synchronized MyDataBase init(Context context) {
        if (instance == null)
            instance = Room.databaseBuilder(context.getApplicationContext()
                    , MyDataBase.class, DBNAME)
                    .addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4)
                    .fallbackToDestructiveMigration()
                    .createFromAsset("mem.db")
                    .build();

        return instance;
    }

    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE user ADD COLUMN sex INTEGER NOT NULL DEFAULT 1");
        }
    };

    static final Migration MIGRATION_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE user ADD COLUMN height INTEGER NOT NULL DEFAULT 1");
        }
    };

    static final Migration MIGRATION_3_4 = new Migration(3, 4) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` 
            // (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT
            // , `age` INTEGER NOT NULL, `sex` INTEGER NOT NULL, `height` INTEGER NOT NULL)",
            //根据schema文件创建新表，注意TEXT不需要加上NOT NULL
            database.execSQL(
                    "CREATE TABLE temp_user (" +
                            "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                            "name TEXT, " +
                            "age INTEGER NOT NULL, " +
                            "sex TEXT DEFAULT 'M', " +
                            "height INTEGER NOT NULL )"
            );
            //数据导入临时表
            database.execSQL("INSERT INTO temp_user (name,age,sex,height)" +
                    "SELECT name,age,sex,height FROM user");
            //丢弃原表
            database.execSQL("DROP TABLE user");
            //临时表重命名
            database.execSQL("ALTER TABLE temp_user RENAME TO user");
        }
    };

    //获取Dao对象
    public abstract UserDao getUserDao();
}
